<template>
  <div class="content-wrapper">
    <ul>
      <div class="input-item">
        <input class="text-input" v-model="phone" placeholder="输入您要绑定的手机号" />
      </div>
      <div class="input-item">
        <input class="text-input short-input" placeholder="输入短信验证码" />
        <div @click="sendVerifyCode" v-if="isEnabled" class="text-input msg-btn">获取验证码</div>
        <div v-else class="text-input msg-btn">{{ waitingTime }}秒后再发送</div>
      </div>
    </ul>
    <div class="button-wrapper">
      <button type="button" @click="bind" class="btn btn-large btn-red">绑定手机号</button>
    </div>
    <div class="footer-wrapper">
      <span>书画点评网 2018 版权所有</span>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import qs from 'qs'


export default {
  name: 'Bind',
  data () {
    return {
      phone: '',
      code: '',
      waitingTime: 0,
      isEnabled: true
    }
  },
  methods: {
    bind: function() {
      if (!this.phone) {
        return this.$toast.fail('请输入手机号')
      }
      if (!this.code) {
        return this.$toast.fail('请输入验证码')
      }
      // 转菊花
      this.$toast.loading({ duration: 0 })
      var that = this
      var params = {
        'phone': this.phone,
        'code': this.code
      }
      this.axios.post('/users/bind/', qs.stringify(params))
      .then(function (res) {
        that.$toast.clear()
        if (res.status === 200) {
          that.$toast.success('手机号绑定成功')
          that.$router.go(-1)
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
        if (error.response) {
          that.$toast.fail(error.response.data.message)
        } else {
          that.$toast.fail('手机号绑定失败')
        }
      })
    },
    timeCount () {
      var that = this
      setTimeout(() => {
        that.waitingTime --
        if (!that.waitingTime) {
          that.isEnabled = true
        } else {
          // 循环
          that.timeCount()
        }
      }, 1000)
    },
    sendVerifyCode: function() {
      if (!this.phone) {
        return this.$toast.fail('请先输入手机号')
      }
      var params = {
        'phone': this.phone,
        'is_register': false
      }
      this.$toast.loading({ duration: 0 })
      var that = this
      this.axios.post('/syetem/sms/verify_mobile_phone/', qs.stringify(params))
      .then(function (res) {
        that.$toast.clear()
        if (res.status === 200) {
          // 启动倒计时
          that.isEnabled = false
          that.waitingTime = 90
          that.timeCount()
          that.$toast.success('短信验证码已发送')
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        that.$toast.fail('请求出错')
      })
    }
  }
}

</script>

<style lang="scss">
@import '../../assets/style/account.scss'
</style>
